package com.sychip.fhc.app.wsn.screen

import android.content.res.Configuration
import android.widget.Toast
import androidx.compose.animation.AnimatedVisibility
import androidx.compose.animation.core.Animatable
import androidx.compose.animation.core.tween
import androidx.compose.animation.expandVertically
import androidx.compose.animation.fadeIn
import androidx.compose.animation.fadeOut
import androidx.compose.animation.shrinkVertically
import androidx.compose.foundation.Image
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.ExperimentalLayoutApi
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.layout.widthIn
import androidx.compose.foundation.layout.wrapContentSize
import androidx.compose.foundation.layout.wrapContentWidth
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.ExperimentalMaterialApi
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Usb
import androidx.compose.material.icons.outlined.ArrowDropUp
import androidx.compose.material.icons.outlined.Settings
import androidx.compose.material.icons.outlined.Verified
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.DividerDefaults
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.MaterialTheme.colorScheme
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.material3.rememberModalBottomSheetState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.MutableState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateListOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.ColorFilter
import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.platform.LocalConfiguration
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import androidx.navigation.NavHostController
import androidx.navigation.compose.rememberNavController
import com.fhc.base.EventBusSubGInfo
import com.fhc.base.LocalManager.stringResource
import com.fhc.base.isTablet
import com.fhc.usb.UsbDeviceDto
import com.fhc.view.FhcAppVersion
import com.fhc.view.FhcBottomSheet
import com.fhc.view.rememberFhcBottomSheetVisibleState
import com.fhc.view.utils.SvgFitWidthIcon
import com.sychip.fhc.IS_DEBUG
import com.sychip.fhc.app.todo.R
import com.sychip.fhc.app.wsn.nav.WsnNavigationItem.NavItem_About
import com.sychip.fhc.app.wsn.screen.components.WsnLicenseView
import com.sychip.fhc.lib.base.FhcTopAppBar
import kotlinx.coroutines.CoroutineScope

@Composable
@OptIn(ExperimentalMaterial3Api::class, ExperimentalLayoutApi::class)
fun WsnAboutScreen(navController: NavHostController = rememberNavController()) {

    val sheetLicenseState = rememberModalBottomSheetState(skipPartiallyExpanded = true)
    val visibleLicenseState = rememberFhcBottomSheetVisibleState()

//    val visibleSubGState = rememberFhcBottomSheetVisibleState()
    val coroutineScope: CoroutineScope = rememberCoroutineScope()
    val navBackStackEntry = remember { navController.currentBackStackEntry }
    val viewModel: WsnAboutViewModel = navBackStackEntry?.let { hiltViewModel(it) } ?: hiltViewModel()

    Scaffold(
        modifier = Modifier.fillMaxSize(),
        topBar = {
            FhcTopAppBar(
                title = NavItem_About.label,
                actions = {
                    IconButton(onClick = {
                        visibleLicenseState.value = true
                    }) {
                        Icon(Icons.Outlined.Verified, null)
                    }
//                    LanguageMenu(
//                        {locale->
//                        Timber.i("LanguageMenu:%s", locale)
//                        LocalManager.setAppLocale(context,locale.language)
//
//                        }
//                    )
                },
            )
        }
    ) { innerPadding ->
        val appSettingFlow by viewModel.appSettingFlow.collectAsStateWithLifecycle()
        val clickTimes = remember { mutableStateListOf<Long>() }

        val context = LocalContext.current

        Box(modifier = Modifier.padding(top = innerPadding.calculateTopPadding()).fillMaxWidth()
            .clickable {
                if(!IS_DEBUG) return@clickable
                val currentTime = System.currentTimeMillis()
                clickTimes.add(currentTime)

                // 移除超过3秒的旧记录
                clickTimes.removeAll { time ->
                    currentTime - time > 3000
                }

                // 当达到5次点击时切换状态
                if (clickTimes.size == 5) {
                    Toast.makeText(
                        context, if(!appSettingFlow.mockMode) "已进入测试模式" else "已退出测试模式", Toast.LENGTH_SHORT
                    ).show()
                    viewModel.toggleMockMode()
                    clickTimes.clear()
                }
            }) {
            AboutContent(modifier = Modifier.fillMaxSize(), //showSubGEditState = visibleSubGState
            )
            FhcBottomSheet(
                title = stringResource(R.string.wsn_app_license),
                sheetState = sheetLicenseState,
                visibleState = visibleLicenseState,
                coroutineScope = coroutineScope
            ) {
                WsnLicenseView()
            }

//            val subG = remember {mutableStateOf(EventBusSubGInfo())}
//            val sheetSubGState = rememberModalBottomSheetState(skipPartiallyExpanded = true,
//                confirmValueChange = {sheetValue ->
//                    true
//                } // 关键！false阻止所有状态变更
//            )
//
//            FhcBottomSheet(
//                title = stringResource(R.string.wsn_subg_setting),
//                sheetState = sheetSubGState,
//                visibleState = visibleSubGState,
//                coroutineScope = coroutineScope,
//                showActionYes = true,
//                onActionYes = {
//                    Timber.e("onActionYes  saveSubGInfo :%s", subG)
//                    viewModel.saveSubGInfo(subG.value)
//                    visibleSubGState.value = false
//                    true
//                },
//            ) {
//                SubGSettingView(subG)
//            }
        }
    }
//    }


}


//
//@Composable
//fun LanguageMenu(
//    onSelected: ((locale: Locale) -> Unit)? = null
//) {
//    val currentLocale = LocalManager.currentLocale.collectAsStateWithLifecycle()
//    val context = LocalContext.current
//    if(onSelected == null){
//        IconButton(onClick = {
//            if(currentLocale.value?.language == Locale.JAPANESE.language) LocalManager.setAppLocale(context,Locale.ENGLISH.language)
//            else LocalManager.setAppLocale(context,Locale.JAPANESE.language)
//        }) {
//            Icon(
//                painterResource(id = if(currentLocale.value?.language == Locale.JAPANESE.language)  R.drawable.ic_lang_jp_en  else R.drawable.ic_lang_en_jp),
//                null
//            )
//        }
//        return
//    }
//    TopAppBarDropdownMenu(
//        iconContent = {
//            Icon(
//                painterResource(id = if(currentLocale.value?.language == Locale.JAPANESE.language)  R.drawable.ic_lang_jp_en  else R.drawable.ic_lang_en_jp),
//                null
//            )
//        }
//    ) { closeMenu ->
//        DropdownMenuItem(
//            modifier = Modifier.wrapContentSize(),
//            onClick = {
//                onSelected(Locale.ENGLISH)
//                closeMenu()
//            },
//            text = {Text(text = "English")},
//
//            trailingIcon = {
//                if(currentLocale.value?.language == Locale.ENGLISH.language){
//                    Icon(
//                        modifier = Modifier.size(20.dp),
//                        imageVector = Icons.Default.Check,
//                        contentDescription = null,
//                        tint = Color.Blue
//                    )
//                }
//            },
//            contentPadding = MenuDefaults.DropdownMenuItemContentPadding,
//        )
//
//        DropdownMenuItem(
//            modifier = Modifier.wrapContentSize(),
//            onClick = {
//                onSelected(Locale.JAPANESE)
//                closeMenu()
//            },
//            text = {Text(text ="日本語")},
//
//            trailingIcon = {
//                if(currentLocale.value?.language == Locale.JAPANESE.language){
//                    Icon(
//                        modifier = Modifier.size(20.dp),
//                        imageVector = Icons.Default.Check,
//                        contentDescription = null,
//                        tint = Color.Blue
//                    )
//                }
//            },
//            contentPadding = MenuDefaults.DropdownMenuItemContentPadding,
//        )
//    }
//}
//


@Composable
@Preview
@OptIn(ExperimentalMaterialApi::class)
private fun AboutContent(
    modifier: Modifier = Modifier,
    //viewModel: WsnAboutViewModel = hiltViewModel(),
    //showSubGEditState : MutableState<Boolean> = remember { mutableStateOf(false) },
) {
    val heroW = if (isTablet())180.dp else 80.dp
    val logoW = if (isTablet())220.dp else 180.dp
    val config = LocalConfiguration.current

    Column(modifier.fillMaxSize().verticalScroll(rememberScrollState())) {
//        Text(
//            modifier = Modifier.padding(16.dp).align(alignment = Alignment.CenterHorizontally),
//            text = stringResource(R.string.wsn_app_name_full),
//            style = MaterialTheme.typography.titleLarge,
//            color = colorScheme.primary
//        )

        SvgFitWidthIcon(
            modifier = Modifier.align(alignment = Alignment.CenterHorizontally).padding(top = 20.dp, bottom = 20.dp),
            path = "svg/logo.svg",
            svgWidth = logoW
        )

        val isExpanded = remember { mutableStateOf(true) }
        Column(modifier = Modifier.weight(1f)) {
            UsbInfoCard(isExpanded = isExpanded)

//            val usbOnline by viewModel.usbOnline.collectAsStateWithLifecycle()
//            if(usbOnline || IS_DEBUG) {
//                Spacer(Modifier.height(10.dp))
//                SubGInfoCard(isExpanded = isExpanded, showSubGEditState= showSubGEditState)
//            }
        }

        if (config.orientation == Configuration.ORIENTATION_PORTRAIT && isTablet()) {
            Image(
                painter = painterResource(id = R.drawable.murata_lala),
                contentDescription = null,
                modifier = Modifier.size(
                    heroW
                ).align(alignment = Alignment.CenterHorizontally).padding(top = 20.dp, bottom = 10.dp),
            )
        }
        FhcAppVersion(R.string.wsn_copyright)
    }
}



@Preview(showBackground = true)
@Composable
private fun UsbInfoCard(viewModel: WsnAboutViewModel = hiltViewModel(),
                        isExpanded: MutableState<Boolean> = remember { mutableStateOf(false) }) {

    val device by viewModel.usbDevice.collectAsStateWithLifecycle()
    val usbOnline by viewModel.usbOnline.collectAsStateWithLifecycle()

    LaunchedEffect(usbOnline) {
        if(usbOnline){
            viewModel.getSubgInfo()
        }
    }

    val startP = 20.dp
    val widthP = 36.dp
    val spaceP = 16.dp
    val rightP = startP + widthP + spaceP

    val modifier = Modifier.fillMaxWidth().padding(top = 16.dp, start = 16.dp, end = 16.dp, bottom = 2.dp)

    val rotation = remember { Animatable(0f) }

    // 动画启动副作用
    LaunchedEffect(isExpanded.value) {
        val targetRotation = if (isExpanded.value) 180f else 0f
        rotation.animateTo(
            targetRotation,
            animationSpec = tween(durationMillis = 300)
        ) {
        }
    }

    val config = LocalConfiguration.current
    Card(modifier = modifier, colors = CardDefaults.cardColors(containerColor = Color.White.copy(alpha = 0.15f))) {
        Row(
            modifier = Modifier.padding(top = 10.dp, bottom = 10.dp, start = startP),
            verticalAlignment = Alignment.CenterVertically
        ) {
            Icon(
                modifier = Modifier.size(widthP),
                imageVector = Icons.Default.Usb,
                contentDescription = null,
                tint = if (usbOnline) Color.White else Color.LightGray,
            )
            Spacer(modifier = Modifier.width(spaceP))
            Row(modifier = Modifier.fillMaxWidth().weight(1f)) {
                Text(
                    modifier = Modifier.weight(1f).align(alignment = Alignment.CenterVertically),
                    text = device?.productName ?: stringResource(R.string.wsn_usb_no_data),
                    style = MaterialTheme.typography.titleSmall,
                    color = colorScheme.onPrimaryContainer,
                    fontWeight = FontWeight.ExtraBold
                )

                Text(
                    modifier = Modifier.padding(end = rightP).align(alignment = Alignment.CenterVertically),
                    text =if (device != null) {
                        if (usbOnline) {
                            stringResource(R.string.wsn_usb_online)
                        } else {
                            stringResource(R.string.wsn_usb_offline)
                        }
                    }else{""},
                    style = MaterialTheme.typography.bodySmall,
                    color = if (usbOnline) Color.White else Color.LightGray,
                )
            }
            if (config.orientation == Configuration.ORIENTATION_LANDSCAPE || !isTablet()) {
                IconButton(
                    modifier = Modifier.padding(end = 6.dp).height(widthP).align(alignment = Alignment.CenterVertically),
                    onClick = {
                        isExpanded.value = !isExpanded.value
                    }) {
                    Icon(Icons.Outlined.ArrowDropUp, null, tint = Color.White,modifier = Modifier.size(32.dp).graphicsLayer {
                        rotationZ = rotation.value
                    })
                }

            }
        }
    }
//        if(isTablet()) {
    if (config.orientation == Configuration.ORIENTATION_PORTRAIT && isTablet()) {
        DeviceDetail(device, rightP)
    }else{
        AnimatedVisibility(
            visible = isExpanded.value,
            enter = expandVertically() + fadeIn(),
            exit = shrinkVertically() + fadeOut()
        ) {
            DeviceDetail(device, rightP)
        }
    }

}


@Composable
private fun DeviceDetail(device: UsbDeviceDto?, leftRightPadding: Dp) {
    var items: List<Pair<String, String>> = listOf(
//        stringResource(R.string.wsn_usb_deviceName) to stringResource(R.string.wsn_usb_no_data),
        stringResource(R.string.wsn_usb_vendorId) to stringResource(R.string.wsn_usb_no_data),
        stringResource(R.string.wsn_usb_productId) to stringResource(R.string.wsn_usb_no_data),
//        stringResource(R.string.wsn_usb_deviceProtocol) to stringResource(R.string.wsn_usb_no_data),
        stringResource(R.string.wsn_usb_manufacturerName) to stringResource(R.string.wsn_usb_no_data),
        stringResource(R.string.wsn_usb_serialNumber) to stringResource(R.string.wsn_usb_no_data),
//        stringResource(R.string.wsn_usb_configurationCount) to stringResource(R.string.wsn_usb_no_data),
    )
    if (device != null) {
        items = listOf(
//            stringResource(R.string.wsn_usb_deviceName) to device.deviceName,
            stringResource(R.string.wsn_usb_vendorId) to "${device.vendorId}",
            stringResource(R.string.wsn_usb_productId) to "${device.productId}",
//            stringResource(R.string.wsn_usb_deviceProtocol) to device.deviceProtocol.toString(),
            stringResource(R.string.wsn_usb_manufacturerName) to (device.manufacturerName ?: stringResource(R.string.wsn_usb_no_data)),
            stringResource(R.string.wsn_usb_serialNumber) to (device.serialNumber ?: stringResource(R.string.wsn_usb_no_data)),
//            stringResource(R.string.wsn_usb_configurationCount) to device.configurationCount.toString()
        )
    }

    Card(
        modifier = Modifier.fillMaxWidth().padding(horizontal = 16.dp).verticalScroll(state = rememberScrollState()),
        colors = CardDefaults.cardColors(containerColor = Color.White.copy(alpha = 0.15f))
    ) {
        Column(
            modifier = Modifier.padding(start = leftRightPadding, end = leftRightPadding, top = 16.dp, bottom = 16.dp)
        ) {
            items.forEach { (label, value) ->
                CardItemRow(label, value)
                HorizontalDivider(
                    modifier = Modifier.padding(vertical = 8.dp),
                    thickness = DividerDefaults.Thickness,
                    color = DividerDefaults.color
                )
            }
        }
    }
}

@Preview(showBackground = true)
@Composable
private fun SubGInfoCard(viewModel: WsnAboutViewModel = hiltViewModel(),
                         isExpanded: MutableState<Boolean> = remember { mutableStateOf(false) },
                         showSubGEditState : MutableState<Boolean> = remember { mutableStateOf(false) }) {

    val subG by viewModel.subG.collectAsStateWithLifecycle()
    Column(modifier = Modifier.fillMaxWidth()) {
        val startP = 20.dp
        val widthP = 36.dp
        val spaceP = 16.dp
        val rightP = startP + widthP + spaceP

        val rotation = remember { Animatable(0f) }

        // 动画启动副作用
        LaunchedEffect(isExpanded.value) {
            val targetRotation = if (!isExpanded.value) 180f else 0f
            rotation.animateTo(
                targetRotation,
                animationSpec = tween(durationMillis = 300)
            ) {
            }
        }
        val config = LocalConfiguration.current
        val modifier = Modifier.fillMaxWidth().padding(top = 16.dp, start = 16.dp, end = 16.dp, bottom = 2.dp)
        Card(modifier = modifier, colors = CardDefaults.cardColors(containerColor = Color.White.copy(alpha = 0.15f))) {
            Row(
                modifier = Modifier.padding(top = 10.dp, bottom = 10.dp, start = startP),
                verticalAlignment = Alignment.CenterVertically
            ) {
                Image(
                    modifier = Modifier.size(widthP),
                    painter = painterResource(id = R.drawable.ic_sensor),
                    colorFilter = ColorFilter.tint(colorScheme.primary),
                    contentDescription = null,
                )
                Spacer(modifier = Modifier.width(spaceP))
                Row(modifier = Modifier.fillMaxWidth().weight(1f)) {
                    Text(
                        modifier = Modifier.weight(1f).align(alignment = Alignment.CenterVertically),
                        text = stringResource(R.string.wsn_subg_title),
                        style = MaterialTheme.typography.titleSmall,
                        color = colorScheme.onPrimaryContainer,
                        fontWeight = FontWeight.ExtraBold
                    )
//                    IconButton(
//                        modifier = Modifier.padding(end = rightP).height(widthP).align(alignment = Alignment.CenterVertically),
//                        onClick = {
//                            showSubGEditState.value = true
//                        }) {
//                        Icon(Icons.Outlined.Settings, null)
//                    }
                }
                if (config.orientation == Configuration.ORIENTATION_LANDSCAPE || !isTablet()) {
                    IconButton(
                        modifier = Modifier.padding(end = 6.dp).height(widthP).align(alignment = Alignment.CenterVertically),
                        onClick = {
                            isExpanded.value = !isExpanded.value
                        }) {
                        Icon(Icons.Outlined.ArrowDropUp, null, tint = Color.White, modifier = Modifier.size(32.dp).graphicsLayer {
                            rotationZ = rotation.value
                        })
                    }

                }
            }
        }
        if (config.orientation == Configuration.ORIENTATION_PORTRAIT && isTablet()) {
            SubGDetail(subG, rightP, rightBottomContent ={
                IconButton(
                    modifier = Modifier.height(widthP),
                    onClick = {
                        showSubGEditState.value = true
                    }) {
                    Icon(Icons.Outlined.Settings, null)
                }
            })
        } else {
            AnimatedVisibility(
                visible = !isExpanded.value,
                enter = expandVertically() + fadeIn(),
                exit = shrinkVertically() + fadeOut()
            ) {
                SubGDetail(subG, rightP, rightBottomContent ={
                    IconButton(
                        modifier = Modifier.height(widthP),
                        onClick = {
                            showSubGEditState.value = true
                        }) {
                        Icon(Icons.Outlined.Settings, null)
                    }
                })
            }
        }
    }
}

@Preview(showBackground = true)
@Composable
private fun SubGDetail(subG: EventBusSubGInfo? = EventBusSubGInfo(), leftRightPadding: Dp = 0.dp, rightBottomContent: @Composable () -> Unit = {}) {
    var items: List<Pair<String, String>> = listOf(
        stringResource(R.string.wsn_subg_channel) to stringResource(R.string.wsn_usb_no_data),
        stringResource(R.string.wsn_subg_port) to stringResource(R.string.wsn_usb_no_data),
        stringResource(R.string.wsn_subg_pan) to stringResource(R.string.wsn_usb_no_data),
        stringResource(R.string.wsn_subg_encryption) to stringResource(R.string.wsn_usb_no_data)
    )
    if (subG != null) {
        items = listOf(
            stringResource(R.string.wsn_subg_channel) to subG.channel,
            stringResource(R.string.wsn_subg_port) to subG.port,
            stringResource(R.string.wsn_subg_pan) to subG.panId,
            stringResource(R.string.wsn_subg_encryption) to if(subG.encryption) stringResource(R.string.wsn_subg_encryption_enable) else stringResource(R.string.wsn_subg_encryption_disable)
        )
    }

    Box(modifier = Modifier.fillMaxWidth()){
        Card(
            modifier = Modifier.fillMaxWidth().padding(horizontal = 16.dp).verticalScroll(state = rememberScrollState()),
            colors = CardDefaults.cardColors(containerColor = Color.White.copy(alpha = 0.15f))
        ) {
            Column(
                modifier = Modifier.padding(start = leftRightPadding, end = leftRightPadding, top = 16.dp, bottom = 16.dp)
            ) {
                items.forEach { (label, value) ->
                    CardItemRow(label, value)
                    HorizontalDivider(
                        modifier = Modifier.padding(vertical = 8.dp),
                        thickness = DividerDefaults.Thickness,
                        color = DividerDefaults.color
                    )
                }
            }
        }
        Box(modifier = Modifier.align(Alignment.BottomEnd).wrapContentSize().padding(end = 32.dp, bottom = 16.dp)) {
            rightBottomContent()
        }
    }
}


@Composable
private fun CardItemRow(label: String, value: String) {
    Row(
        modifier = Modifier.fillMaxWidth(),
        horizontalArrangement = Arrangement.SpaceBetween
    ) {
        Text(
            modifier = Modifier.wrapContentWidth().widthIn(min = 160.dp),
            text = label,
            style = MaterialTheme.typography.bodyMedium,
            color = colorScheme.onPrimaryContainer
        )
        Text(
            text = value,
            style = MaterialTheme.typography.bodySmall,
            color = colorScheme.onPrimaryContainer.copy(alpha = 0.8f),
            textAlign = TextAlign.End
        )
    }
}
